package com.gycode.vpush.consumer.listenter;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.gycode.vpush.consumer.handler.base.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

@Component
public class MyMessageListener implements MessageListener {
    private static final Logger LOG = LoggerFactory.getLogger(MyMessageListener.class);

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public Action consume(Message msg, ConsumeContext ctx) {
        LOG.info("message :{}",msg);
        String tag = msg.getTag();
        String key = msg.getKey();
        String logId = null;
        Handler handler = null;
        try {
            handler = (Handler) applicationContext.getBean(String.format("handler_%s", tag));
            logId = handler.createLogId();
            if (handler.handle(key, new String(msg.getBody(), Charset.forName("UTF-8")))) {
                return Action.CommitMessage;
            } else {
                return Action.ReconsumeLater;
            }
        } catch (NoSuchBeanDefinitionException e2) {
            return Action.CommitMessage;
        } catch (Exception e) {
            if (handler != null) {
                try {
                    LOG.error(String.format("[logId: %s] [msgId: %s] [ip: %s] [data: %s] %s", logId, msg.getMsgID(), InetAddress.getLocalHost().getHostAddress(), handler.getLogData(), e.getMessage()), e);
                } catch (UnknownHostException ex) {
                    LOG.error(ex.getMessage(), e);
                }
                handler.setLogData("");
            } else {
                LOG.error(e.getMessage(), e);
            }
            // return Action.CommitMessage;
            return Action.ReconsumeLater;
        }
    }
}
